package com.astrocsr.security;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import com.astrocsr.business.UserManager;
import com.astrocsr.common.helper.EncryptionHelper;
import com.astrocsr.domain.web.UserInfo;

public class AuthenticationCustomProvider implements AuthenticationProvider {
 
	static final Logger log = Logger.getLogger(AuthenticationCustomProvider.class);

	@Autowired
	private UserManager userManager;
	
	@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    	
    	try {
	        String username = authentication.getName();
	        String password = (String) authentication.getCredentials();
	
	        UserInfo details = userManager.getUserByEmail(username);

	        if (details != null && details.getPassword() != null &&
	        		details.getPassword().equals(EncryptionHelper.encodeMD5(password))) {
			    WebUserDetails principal = new AppWebUserDetails(details, details.getRole());

			    return new UsernamePasswordAuthenticationToken(principal, password, principal.getAuthorities());	
	        }
	        throw new BadCredentialsException("Authentication Fail");
		    
    	} catch(Exception e) {
    		//e.printStackTrace();
			throw new BadCredentialsException(e.getMessage());
    	} finally {

    	}
    }
 
    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}